package model;

import java.util.Date;
import java.util.GregorianCalendar;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

import toolkit.Parse;

@Entity
@DiscriminatorValue("1")
public class Player extends User implements PlayerInterface
{
	private static final long serialVersionUID = 1L;
	
	private static final double REBUY = 1000;
	
	private static final int REBUY_INTERVAL = 1000 * 60 * 60 * 5;
	
	private int playerId;

	@Column(nullable=false)
	private GregorianCalendar birthday;
	
	@Column(nullable=false)
	private double balance;
	
	private GregorianCalendar rebuy;
	
	@OneToOne(targetEntity=Settings.class, fetch=FetchType.EAGER)
	@JoinColumn(name="settingsId")
	private SettingsInterface settings;

	@Column(nullable=false)
	private boolean banned = false;
	
	public Player()
	{
		
	}
	
	public Player(String username)
	{
		super(username);
	}
	
	public int getId()
	{
		return playerId;
	}
	
	public void setBirthday(String birthday)
	{
		setBirthday(Parse.toDate(birthday));
	}
	
	public void setBirthday(Date birthday)
	{
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(birthday);
		
		setBirthday(calendar);
	}

	public void setBirthday(GregorianCalendar birthday)
	{
		this.birthday = birthday;
	}
	
	public GregorianCalendar getBirthday()
	{
		return birthday;
	}
	
	public boolean checkBalance(double buyin)
	{
		if (balance >= buyin)
		{
			return true;
		}
		
		if (checkRebuy())
		{
			if (balance >= buyin)
			{
				return true;
			}
		}
			
		return false;
	}
	
	public void updateBalance(double delta)
	{
		balance += delta;
		
		// You cannot have a negative balance in our game.
		if (balance < 0)
		{
			balance = 0;
		}
	}
	
	public double getBalance()
	{
		return balance;
	}
	
	public boolean checkRebuy()
	{
		if (balance >= REBUY)
		{
			return false;
		}
		
		GregorianCalendar current = new GregorianCalendar();
		
		if (rebuy == null || current.getTimeInMillis() - rebuy.getTimeInMillis() >= REBUY_INTERVAL)
		{
			rebuy = current;
			
			balance = REBUY;
			
			return true;
		}
		
		return false;
	}
	
	public void setSettings(SettingsInterface settings)
	{
		this.settings = settings;
	}
	
	public SettingsInterface getSettings()
	{
		return settings;
	}

	public void setBanned(boolean banned)
	{
		this.banned = banned;
	}
	
	public boolean isBanned()
	{
		return banned;
	}
	
	public boolean check()
	{
		return true;
	}
	
	public String toString()
	{
		return username;
	}
}
